package com.fast.common.utils;


import com.fast.common.constant.RedisKeyConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@Data
public class AuthUtils {

    public final static String SECRET = "jflsjflksjflkas";
    /**
     * 过期时长，单位为秒,可以通过配置写入。
     */
    @Value("${jwt.token.expiration}")
    private int expiration;

    public String getAccessTokenKey(Object sub) {
        return RedisKeyConstant.REDISKEY + "_" + sub;
    }

    public String build(Object id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.ID, id);
        claims.put(Claims.ISSUED_AT, new Date());
        claims.put(Claims.ISSUER, "");
        return build(claims);
    }

    public String build(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * to validate and read the JWT
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            //This line will throw an exception if it is not a signed JWS (as expected)
            claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("error token: " + token, e);
            claims = null;
        }
        return claims;
    }


}
